package com.lc.rocketmq.service;

import com.lc.rocketmq.dao.OrderDao;
import com.lc.rocketmq.po.Order;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author liuc
 * @date 2021/8/21
 * @description
 **/
@Slf4j
@Service
public class OrderService {

    @Autowired
    private OrderDao orderDao;

    public Order get(Long id){
        return orderDao.getOne(id);
    }

    public Order get(Long userId, Long goodsId){
        return orderDao.findByUserIdAndGoodsId(userId,goodsId,2);
    }

    public Order add(Long userId, Long goodsId){
        Order order = new Order();
        order.setUserId(userId);
        order.setGoodsId(goodsId);
        order.setNum(1);
        Date date = new Date();
        order.setCreateTime(date);
        //0: 新建 1:完成
        // 2:过期(支付) 3:失效(其他原因)
        order.setStatus(0);
        orderDao.save(order);
        return order;
    }

    //查询订单状态
    public int status(Long orderId){
        Order order = orderDao.findById(orderId).orElse(null);
        //-1没有找到
        return order == null ? -1 : order.getStatus();
    }

    //过期
    public boolean timeout(Long orderId){
        //乐观锁更新 2:过期 0:新建
        return orderDao.setStatus(orderId,2,0) > 0;
    }

    //订单失效
    public boolean fail(Long orderId){
        //乐观锁更新
        return orderDao.setStatus(orderId,3,0) > 0;
    }

    //支付
    public boolean pay(Long orderId){
        //乐观锁更新
        return orderDao.pay(orderId,1,0) > 0;
    }
}
